import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, EventEmitter, Output } from '@angular/core';
import { ConfirmationService } from 'primeng/api';
import { FieldType, SiteOrientation } from 'src/components/scenarios/enums';
import { FieldMapConfig, SiteNodeConfig } from 'src/components/scenarios/models';
import { v4 as guid } from "uuid";

@Component({
  selector: 'app-site-setting',
  templateUrl: './site-setting.component.html',
  styleUrl: './site-setting.component.scss'
})
export class SiteSettingComponent {
  sidebarVisible: boolean = false;
  cfg?: SiteNodeConfig;

  types: FieldType[] = Object.values(FieldType);
  orientations: SiteOrientation[] = Object.values(SiteOrientation);

  @Output()
  onHide: EventEmitter<SiteNodeConfig> = new EventEmitter();

  constructor(private confirmService: ConfirmationService) {
  }

  onEdit(cfg: SiteNodeConfig) {
    this.cfg = { ...cfg };
    this.sidebarVisible = true;
  }
  onSidebarHide() {
    this.onHide.next(this.cfg!);
    this.cfg = undefined;
  }

  onFiedEditConfirm(field: FieldMapConfig) {
    if (field.Id) {
      this.cfg!.Fields = this.cfg!.Fields.map(f => f.Id === field.Id ? field : f);
    }
    else {
      this.cfg?.Fields.push({ ...field, Id: guid() });
    }
  }

  onDeleteField(field: FieldMapConfig) {
    this.confirmService.confirm({
      message: 'Do you want to delete this field?',
      header: 'Delete Confirmation',
      icon: 'pi pi-info-circle',
      acceptButtonStyleClass: "p-button-danger p-button-text",
      rejectButtonStyleClass: "p-button-text p-button-text",
      acceptIcon: "none",
      rejectIcon: "none",

      accept: () => {
        this.cfg!.Fields = this.cfg!.Fields.filter(f => f.Id !== field.Id);
      },
      reject: () => {
      }
    });
  }

  onDragDrop(event: CdkDragDrop<FieldMapConfig[]>) {
    moveItemInArray(this.cfg!.Fields, event.previousIndex, event.currentIndex);
  }
}
